//
//  RHDeviceListViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/25.
//

#import "RHDeviceListViewController.h"
#import "RHDeviceListCell.h"
#import "RHDeviceStatusVC.h"
#import "RHDeviceModel.h"
#import <MGSwipeTableCell.h>
#import "RHDeviceBindVC.h"
#import "RHSearchView.h"
#import "RHAlertView.h"

@interface RHDeviceListViewController ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic ,copy) NSString *keyCode;

@property (nonatomic, strong) RHSearchView *searchView;
@end

@implementation RHDeviceListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _deviceListArr = [NSMutableArray array];
    [self.view setBackgroundColor:CFTabViewBgColor];
    [self.navigationItem setTitle:self.titleStr?self.titleStr:@"设备列表".rh_localized];
    self.currentPage = 1;
    self.numOfPage = 10;
    self.requestType = RequestTypeRefresh;
    [self setupUI];
    [self getDeviceList];
    
}
-(void)setDeviceListArr:(NSMutableArray *)deviceListArr
{
    _deviceListArr = deviceListArr;
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deviceCountDidChange) name:DeviceListNeedUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getDeviceList) name:UserModifyDeviceName object:nil];
    if(self.showAddBtn){
        UIBarButtonItem *rightBtn = [UIBarButtonItem itemWithImage:@"repair_add" ImageHighLight:@"repair_add" Target:self Seletor:@selector(bindDeviceToPlant) CGRect:CGRectMake(0, 0, 35, 35)];
        self.navigationItem.rightBarButtonItem = rightBtn;
    }
    
    //巡检报表进来
    if (self.devReportSelectBlock){
        _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
        [self.view addSubview:_searchView];
        _searchView.delegate = self;
        _searchView.searchTextField.placeholder = @"请输入设备ID".rh_localized;
    }
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHDeviceListCell class] forCellReuseIdentifier:@"RHDeviceListCell"];
    [_tableView registerClass:[RHDeviceListCell class] forCellReuseIdentifier:@"RHDeviceListCell_noPlantName"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    kWeakSelf;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        if (weakSelf.devReportSelectBlock) {
            make.top.equalTo(weakSelf.searchView.mas_bottom);
        }else{
            make.top.mas_offset(0);
        }
    }];
   
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        weakSelf.keyCode = @"";
        [weakSelf getDeviceList];
        if(weakSelf.refreshBlock){
            weakSelf.refreshBlock();
        }
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getDeviceList];
    }];
}
#pragma mark ------- action ----------
-(void)bindDeviceToPlant
{
    RHDeviceBindVC *vc = [[RHDeviceBindVC alloc]init];
    vc.plantModel = self.plantModel;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)searchDeviceWithKeyCode:(NSString*)keyCode
{
    self.currentPage = 1;
    self.requestType = RequestTypeRefresh;
    [self.tableView endFooterResetNoMoreData];
    self.keyCode = keyCode;
    [self getDeviceList];
}

//自己添加设备成功后
-(void)updateDeviceList
{
    [self searchDeviceWithKeyCode:self.keyCode];
}

//分发设备成功
-(void)deviceCountDidChange
{
    [self getDeviceList];
    if(self.refreshBlock){
        self.refreshBlock();
    }
}

//添加设备  设备分发成功后更新列表
-(void)getDeviceList
{
    if(self.plantModel){
        [self getDeviceOfPlant];
    }else{
        [self getDeviceListOfUser];
    }
}

#pragma mark ----- 获取用户设备列表 ------
-(void)getDeviceListOfUser
{
    NSString *status = @"";
    switch (self.listType) {
        case DevListTypeAll:
            status = @"";
            break;
        case DevListTypeOnline:
            status = @"0";
            break;
        case DevListTypeOffline:
            status = @"1";
            break;
        case DevListTypeFault:
            status = @"2";
            break;
        case DevListTypeAlarm:
            status = @"3";
        default:
            break;
    }
    
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"userId":@(_userId),
                           @"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"status":status,
                           @"deviceId":ValidNullData(self.keyCode)
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_deviceList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                self.deviceListArr = arr;
            }else{//上拉加载
                [self.deviceListArr addObjectsFromArray:arr];
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshCustomWithNoMoreData];
            }
            [self.tableView reloadData];
           
            if(self.deviceListArr.count == 0){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           [self.tableView endHeaderRefresh];
           [self.tableView endFooterRefresh];
    }];
}


#pragma mark ---- 获取电站下的设备 -------
-(void)getDeviceOfPlant
{
    NSString *status = @"";
    switch (self.listType) {
        case DevListTypeAll:
            status = @"";
            break;
        case DevListTypeOnline:
            status = @"0";
            break;
        case DevListTypeOffline:
            status = @"1";
            break;
        case DevListTypeFault:
            status = @"2";
            break;
        case DevListTypeAlarm:
            status = @"3";
            break;
        default:
            break;
    }
    
    NSDictionary *para = @{@"plantId":@(self.plantModel.plant_id),
                           @"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"status":status,
                           @"deviceId":ValidNullData(self.keyCode)
    };
    [QMUITips showLoadingInView:self.view];
    [RHDeviceModel startGetWithCompletionAPIKey:H_getPlantDeviceListByStatus argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                [self.tableView endHeaderRefresh];
                self.deviceListArr = arr;
            }else{//上拉加载
                [self.tableView endFooterRefresh];
                [self.deviceListArr addObjectsFromArray:arr];
                
            }
            [self.tableView reloadData];
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
            if(self.deviceListArr.count == 0){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        [self.tableView endFooterRefresh];
    }];
}

#pragma mark ------ 删除电站下的设备 -----
-(void)deleteDeviceFromPlantWithIndex:(NSUInteger)index
{
    RHDeviceModel *device = self.deviceListArr[index];
    [QMUITips showLoading:@"delete device..." inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_removePlantDevice argument:@{@"deviceId":device.deviceId,@"plantId":@(self.plantModel.plant_id)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter]postNotificationName:DeviceListNeedUpdateNotification object:nil];
            });
           
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

#pragma mark ------ 上级收回已经分发给下级的设备,相当于下级用户解绑设备
-(void)retrievreDeviceWithIndex:(NSUInteger)index
{
    RHDeviceModel *device = self.deviceListArr[index];
    [QMUITips showLoading:@"" inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_deviceUnBind argument:@{@"id":@(device.device_id),@"userId":@(self.userId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功" inView:self.view hideAfterDelay:1];
            [self.deviceListArr removeObject:device];
            [self.tableView reloadData];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if(self.refreshBlock){
                    self.refreshBlock();
                }
                [[NSNotificationCenter defaultCenter]postNotificationName:DeviceListNeedUpdateNotification object:nil];
            });
            
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}


-(void)modifyDeviceNameAction:(RHDeviceModel*)devModel
{
    kWeakSelf;
    RHAlertView *alertView = [[RHAlertView alloc]initWithType:RHAlertTypeTextView title:@"修改设备名称".rh_localized subTitle:nil];
    [alertView setDefaultText:devModel.deviceName];
    alertView.sureBlock = ^(NSString * _Nonnull content) {
        [weakSelf modifyDeviceName:content deviceId:devModel.deviceId];
    };
    [alertView show];
}

#pragma mark ----- 修改设备名
-(void)modifyDeviceName:(NSString*)devName deviceId:(NSString*)deviceId
{
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startPutWithCompletionAPIKey:H_modifyDeviceName argument:@{@"deviceId":deviceId,@"deviceName":devName} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //通知其他列表更新
                [kNotificationCenter postNotificationName:UserModifyDeviceName object:nil];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.deviceListArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceListCell *cell;
    if (self.plantModel) {
        //电站详情进去时设备列表不展示电站名称
        cell = [tableView dequeueReusableCellWithIdentifier:@"RHDeviceListCell_noPlantName"];
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"RHDeviceListCell"];
    }
    cell.listType = self.listType;
    RHDeviceModel *device = self.deviceListArr[indexPath.row];
    cell.device = device;

    __block NSUInteger index = indexPath.row;
    kWeakSelf;
    if(self.canDelete){
        
        MGSwipeButton *oneBtn = [MGSwipeButton buttonWithTitle:@"   " icon:[UIImage imageNamed:@"plant_device_unbind"] backgroundColor:CFTabViewBgColor padding:15 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
            QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:NULL];
            QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                if(weakSelf.plantModel){
                    //解绑电站下的设备
                    [weakSelf deleteDeviceFromPlantWithIndex:index];
                }else{
                    //解绑用户下的设备
                    [weakSelf retrievreDeviceWithIndex:index];
                }
            }];
            QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"确定解绑此设备?".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
            [alertController addAction:action1];
            [alertController addAction:action2];
            [alertController showWithAnimated:YES];
            
            return YES;
        }];
        cell.rightButtons = @[oneBtn];
    }
    
    cell.modifyBlock = ^() {
        [weakSelf modifyDeviceNameAction:device];
    };
    //电站下的设备列表隐藏编辑按钮
    if (self.plantModel) {
        [cell hideEditButton];
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceModel *device = self.deviceListArr[indexPath.row];
    if(self.selectBlock){
        self.selectBlock(device.deviceId);
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    //巡检报表选择
    if(self.devReportSelectBlock){
        self.devReportSelectBlock(device);
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    if(device.lastOnlineTime == 0){
        [QMUITips showError:@"请让设备先连接云平台".rh_localized];
        return;
    }
    RHDeviceStatusVC *vc = [[RHDeviceStatusVC alloc] init];
    vc.deviceModel = device;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ------- textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.keyCode = textField.text;
    [self getDeviceList];
    [self.searchView resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.keyCode = @"";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getDeviceList];
        [self.searchView resignFirstResponder];
    });
    return YES;
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
